<template>
  <div class="chart-container" ref="chartEl"></div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import * as echarts from 'echarts';
import { ECharts } from 'echarts';
import { T_srv, Tsrv, N_RectifierSettings, vue } from '../config';

@T_srv.comp
export default class BaseChart extends vue {
  @T_srv.prop({ type: String, required: true }) readonly title!: string;

  @T_srv.prop({ type: Array, required: true }) readonly data!: any[];

  @T_srv.prop({ type: Array, required: true }) readonly colorPalette!: string[];

  private chartInstance: ECharts | null = null;

  private chartOptions: any = {};

  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  }

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chartInstance?.dispose();
  }

  private initChart() {
    this.chartInstance = echarts.init(this.$refs.chartEl as HTMLElement);
    this.updateChartOptions();
    this.chartInstance.setOption(this.chartOptions);
  }

  @Watch('data', { deep: true })
  private updateChartOptions(forceUpdate = false) {
    this.chartOptions = {
      title: {
        text: this.title,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'time',
        boundaryGap: false,
        data: this.data[0]?.values?.map(item => item[0]) || []
      },
      yAxis: {
        type: 'value'
      },
      series: this.data.map((series, index) => {
        if (series.active) {
          return {
            name: series.name,
            type: 'line',
            data: series.values,
            lineStyle: {
              color: this.colorPalette[index % this.colorPalette.length]
            },
            showSymbol: false
          };
        }
        return null;
      })
    };

    if (this.chartInstance) {
      this.chartInstance.setOption(this.chartOptions, {
        notMerge: forceUpdate
      });
    }
  }

  private handleResize() {
    this.chartInstance?.resize();
  }
}
</script>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 90%;
  margin: 20px 0;
}
</style>
